const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
import Dialog from '../../../../../../ucenter/lib/vant/dialog/dialog';
const app = getApp();
const cityUtil = require('../../../../../../utils/city.js');
var newarr = cityUtil.getDateByLevelType(1);
Page({
  data: {
    //地址Id
    addrId: '',
    //收货人姓名
    name: '',
    //收货人性别
    gender: '',
    //收货人电话
    phone: '',
    //获取用户选择省ID
    provinceId:'',
    //获取用户选择市ID
    cityId: '',
    //获取用户选择区ID
    areaId: '',
    //获取输入的详细地址
    address: '',
    //获取输入的邮编
    postcode: '',
    //带省市区的详细地址
    addressCity: '',
    //地址别名
    addressName:'',
    //是否设置为默认地址
    isDefault: 0,
    //用户地址列表
    addrarr: [],
    //是否开启新增地址
    openAdd: false,
    //是否开启保存地址
    openSave: false,
    //折叠面板
    selectPanel:null,
    //默认地址选择
    regionIndex: [],
    //默认地址
    regionArray: [['请选择'], [], []],
    //获取市级
    cityarr: null,
    //获取区/镇级
    region: null,
    //是否打开选项
    xxshow: false,
    //打开选项的index
    xxindex: null,
    //是否显示文本域
    kqsrk: false,
  },
  //首次加载
  onLoad: function () {
    var _this = this
    _this.setData({
      logininfo: app.globalData.logininfo,
    });
    var arr = _this.data.regionArray
    for (var i = 0; i <= newarr.length - 1; i++) {
      arr[0].push(newarr[i].cityname)
    }
    _this.setData({ 
      regionArray: arr
    })
    var openid = app.globalData.logininfo.openid;
    var data = {};
    console.log(openid)
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.GetBasAddressByUser, data).then(function (res) {
          if (res.code == 200) {
            
            if (res.result.list.length>0){
              _this.setData({
                addrarr: res.result.list
              })
              _this.checkaddrarr();
              console.log(res.result.list)
            }else{
              var arr = _this.data.addrarr
              arr.push({ "gender": app.globalData.logininfo.homeInfo.sex,"isDefault": 1})
              _this.setData({
                addrarr: arr
              })
              _this.checkaddrarr();
            }
          }
        });
      });
    }
  },
  //新增地址
  addaddr: function () {
    var _this = this
    var arr = _this.data.addrarr
    arr.push({ "gender": app.globalData.logininfo.homeInfo.sex})
    this.setData({
      addrarr: arr
    })
    _this.checkaddrarr();
  },
  //确认保存
  yessave: function (e) {
    var _this = this
    var openid = app.globalData.logininfo.openid;
    var data = {};
    var arr = _this.data.addrarr
    var sIndex = _this.data.selectPanel
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        if (arr[sIndex].id == null || arr[sIndex].id == '') {
          data.param = JSON.stringify({
            /*"name": arr[sIndex].name,
            "gender": arr[sIndex].gender,
            "phone": arr[sIndex].phone,
            "provinceId": arr[sIndex].provinceId,
            "cityId": arr[sIndex].cityId,
            "areaId": arr[sIndex].areaId,
            "address": arr[sIndex].address, 
            "postcode": arr[sIndex].postcode,
            "addressCity": arr[sIndex].addressName + arr[sIndex].address, 
            "addressName": arr[sIndex].addressName*/
            "type": 2,
            "name": arr[sIndex].name,
            "gender": arr[sIndex].gender,
            "phone": arr[sIndex].phone,
            "addName": arr[sIndex].addName,
            "latitude": arr[sIndex].latitude,
            "longitude": arr[sIndex].longitude,
            "address": arr[sIndex].address,
            "postcode": arr[sIndex].postcode,
            "isDefault": arr[sIndex].isDefault,
            "addressCity": arr[sIndex].addAddress + arr[sIndex].address, 
          })
          util.post(api.InsertBasAddressByUser, data).then(function (res) {
            if (res.code == 200) {
              _this.onLoad()
              console.log(res)
            }
          });
        } else {
          data.param = JSON.stringify({
            "id": arr[sIndex].id,
            /*"name": arr[sIndex].name,
            "gender": arr[sIndex].gender,
            "phone": arr[sIndex].phone,
            "provinceId": arr[sIndex].provinceId,
            "cityId": arr[sIndex].cityId,
            "areaId": arr[sIndex].areaId,
            "address": arr[sIndex].address,
            "postcode": arr[sIndex].postcode,
            "addressCity": arr[sIndex].addressName + arr[sIndex].address,
            "addressName": arr[sIndex].addressName*/
            "type": 2,
            "name": arr[sIndex].name,
            "gender": arr[sIndex].gender,
            "phone": arr[sIndex].phone,
            "addName": arr[sIndex].addName,
            "latitude": arr[sIndex].latitude,
            "longitude": arr[sIndex].longitude,
            "address": arr[sIndex].address,
            "postcode": arr[sIndex].postcode,
            "isDefault": arr[sIndex].isDefault,
            "addressCity": arr[sIndex].addAddress + arr[sIndex].address, 
          })
          util.post(api.InsertBasAddressByUser, data).then(function (res) {
            if (res.code == 200) {
              _this.onLoad()
              console.log(res)
            }
          });
        }
      });
    }
    _this.setData({
      selectPanel: null,
    })
  },
  //灰色保存
  nosave: function () {
    wx: wx.showToast({
      title: '请完善地址信息',
      icon: 'none',
      duration: 1500
    })
  },
  //取消保存
  canceladdr: function (e) {
    var _this = this
    var arr = _this.data.addrarr
    var sIndex = _this.data.selectPanel
    arr[sIndex].addName = null;
    arr[sIndex].latitude = null;
    arr[sIndex].longitude = null;
    arr[sIndex].address = null;
    arr[sIndex].postcode = null;
    arr[sIndex].addAddress = null;
    _this.setData({
      addrarr : arr
    })
    _this.checkaddr();
    _this.checkaddrarr();
  },
  //选择展开面板
  selectP: function (e) {
    var sIndex = e.target.dataset.index
    var _this = this
    if (sIndex != _this.data.selectPanel) {
      _this.setData({
        selectPanel: sIndex,
      })
      _this.checkaddr();
    } else {
      _this.setData({
        selectPanel: null,
      })
    }
  },
  //检测单个地址信息是否完整
  checkaddr: function (e) {
    var _this = this
    var onIdnex = _this.data.selectPanel
    var arr = _this.data.addrarr
    var name = arr[onIdnex].name
    var gender = arr[onIdnex].gender
    var phone = arr[onIdnex].phone
    var addName = arr[onIdnex].addName
    var address = arr[onIdnex].address
    var postcode = arr[onIdnex].postcode
    if (name != '' && name != null && phone != '' && phone != null && addName != '' && addName != null && address != '' && address != null && postcode != '' && postcode != null) {
      _this.setData({
        openSave: true
      })
    }else{
      _this.setData({
        openSave: false
      })
    }
  },
  //检测列表地址是否完善
  checkaddrarr: function () {
    var _this = this
    var arr = _this.data.addrarr
    if (arr.length==0){
      this.setData({
        openAdd: true
      })
    }else{
      var a = 0;
      for(var i = 0;i<arr.length;i++){
        if (arr[i].addressCity == '' || arr[i].addressCity == null || arr[i].name == '' || arr[i].name == null || arr[i].phone == '' || arr[i].phone == null || arr[i].gender == '' || arr[i].gender == null){
          a++
        }
      }
      if(a>0){
        this.setData({
          openAdd: false
        })
      }else{
        this.setData({
          openAdd: true
        })
      }
    }
  },
  //获取下级
  bindMultiPickerColumnChange: function (e) {
    var rColumn = e.detail.column
    if (rColumn == 0) {
      var rIndex = e.detail.value
      var rName = this.data.regionArray[0][rIndex]
      for (var i = 0; i <= newarr.length - 1; i++) {
        if (newarr[i].cityname == rName) {
          var rId = newarr[i].cityid
        }
      }
      this.setData({
        cityarr: cityUtil.getCityByFatherid(2, rId)
      })
      var arr = this.data.regionArray
      arr[1] = []
      arr[2] = []
      arr[1].push("请选择")
      for (var i = 0; i <= this.data.cityarr.length - 1; i++) {
        arr[1].push(this.data.cityarr[i].cityname)
      }
      var qIndex = this.data.regionIndex
      qIndex[0] = rIndex
      qIndex[1] = 0
      qIndex[1] = 0
      this.setData({
        regionArray: arr,
        regionIndex: qIndex
      })
    }
    if (rColumn == 1) {
      if (this.data.cityarr != null && this.data.cityarr != '') {
        var rIndex = e.detail.value
        var rName = this.data.regionArray[1][rIndex]
        for (var i = 0; i <= this.data.cityarr.length - 1; i++) {
          if (this.data.cityarr[i].cityname == rName) {
            var rId = this.data.cityarr[i].cityid
          }
        }
        this.setData({
          region: cityUtil.getCityByFatherid(3, rId)
        })
        var arr = this.data.regionArray
        arr[2] = []
        arr[2].push("请选择")
        for (var i = 0; i <= this.data.region.length - 1; i++) {
          arr[2].push(this.data.region[i].cityname)
        }
        var qIndex = this.data.regionIndex
        qIndex[1] = rIndex
        qIndex[2] = 0
        this.setData({
          regionArray: arr,
          regionIndex: qIndex
        })
      }
    }
    if (rColumn == 2) {
      if (this.data.region != null && this.data.region != '') {
        var rIndex = e.detail.value
        var rName = this.data.regionArray[2][rIndex]
        for (var i = 0; i <= this.data.region.length - 1; i++) {
          if (this.data.region[i].cityname == rName) {
            var rId = this.data.region[i].cityid
          }
        }
      }
    }
  },
  //确认地址
  bindMultiPickerChange: function (e) {
    var _this = this
    var sIndex = e.target.dataset.index
    var sId = e.target.dataset.id
    var arr = _this.data.addrarr
    var sValue = e.detail.value
    var shengIndex = parseInt(sValue[0]) - 1
    var shiIndex = parseInt(sValue[1]) - 1
    var quIndex = parseInt(sValue[2]) - 1
    var cit = _this.data.cityarr
    var rig = _this.data.region
    if (quIndex >= 0) {
      var qu = rig[quIndex]
      var shi = cit[shiIndex]
      var sheng = newarr[shengIndex]
      var areaId = qu.cityid
      var areaName = qu.cityname
      var cityId = shi.cityid
      var cityName = shi.cityname
      var provinceId = sheng.cityid
      var provinceName = sheng.cityname
      arr[sIndex].areaId = qu.cityid
      arr[sIndex].cityId = shi.cityid
      arr[sIndex].provinceId = sheng.cityid
      arr[sIndex].addressName = provinceName + cityName + areaName
      _this.setData({
        addrarr: arr
      })
    } else {
      wx.showToast({
        title: '请选择完善的地址',
        icon: 'none',
        duration: 1500
      })
    }
    _this.checkaddr();
  },
  //开启输入框
  kqsrk: function(){
    this.setData({
      kqsrk: true
    })
  },
  //获取输入的详细地址
  updatedetails: function (e) {
    var _this = this
    _this.setData({
      kqsrk: false
    })
    var dIndex = e.target.dataset.index
    var dId = e.target.dataset.id
    var arr = _this.data.addrarr
    var dValue = e.detail.value.replace(/\s+/g, '')
    if (dValue != null && dValue != '') {
      arr[dIndex].address = dValue
      _this.setData({
        addrarr: arr
      })
    } else {
      wx: wx.showToast({
        title: '详细地址不能为空',
        icon: 'none',
        duration: 1500
      })
    }
    _this.checkaddr();
  },
  //获取输入的姓名，电话，邮政编码
  updatepostal: function (e) {
    var _this = this
    var pName = e.target.dataset.name
    var pIndex = e.target.dataset.index
    var pId = e.target.dataset.id
    var arr = _this.data.addrarr
    var pValue = e.detail.value.replace(/\s+/g, '')
    var pLength = pValue.length
    if (pName=='name'){
      arr[pIndex].name = pValue
      _this.setData({
        addrarr: arr
      })
    }
    if (pName == 'phone'){
      if (!(/^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/.test(pValue))) {
        wx: wx.showToast({
          title: '请输入正确的电话',
          icon: 'none',
          duration: 1500
        })
      } else {
        arr[pIndex].phone = pValue
        _this.setData({
          addrarr: arr
        })
      }
    }
    if (pName == 'postcode'){
      if (pLength == 6) {
        arr[pIndex].postcode = pValue
        _this.setData({
          addrarr: arr
        })
      } else {
        wx: wx.showToast({
          title: '请输入正确的邮编',
          icon: 'none',
          duration: 1500
        })
      }
    }
    _this.checkaddr();
  },
  //获取性别
  updategender: function(e){
    var _this = this
    var pGender = e.target.dataset.gender
    var pIndex = e.target.dataset.index
    var pId = e.target.dataset.id
    var arr = _this.data.addrarr
    arr[pIndex].gender = pGender
    _this.setData({
      addrarr: arr
    })
    _this.checkaddr();
  },
  //开启选项窗口
  openxx: function (e) {
    var _this = this
    var oId = e.currentTarget.dataset.id
    var oIndex = e.currentTarget.dataset.index
    this.setData({
      xxindex: oIndex,
      xxshow: true
    })
  },
  //关闭选项窗口
  closePop: function () {
    this.setData({
      xxindex: null,
      xxshow: false
    })
  },
  //设置默认地址
  setdefaultAddr: function (e) {
    var _this = this
    var oIndex = e.currentTarget.dataset.index
    var arr = _this.data.addrarr
    var openid = app.globalData.logininfo.openid;
    var data = {};
    if (arr[oIndex].id != null && arr[oIndex].id != ''){
      for (var i = 0; i < arr.length; i++) {
        arr[i].isDefault = 0
      }
      arr[oIndex].isDefault = 1
      if (openid != null && openid != "") {
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          for (var i = 0; i < arr.length; i++) {
            if (arr[i].id != null && arr[i].id != '') {
              data.openid = openid;
              data.access_token = res.access_token;
              data.param = JSON.stringify({
                "id": arr[i].id,
                "isDefault": arr[i].isDefault,
              })
              util.post(api.InsertBasAddressByUser, data).then(function (res) {
                if (res.code == 200) {
                  _this.setData({
                    addrarr: arr
                  })
                }
              });
            }
          }
        });
      }
    }else{
      wx.showToast({
        title: '请先保存该地址',
        icon: 'none',
        duration: 1500
      })
    }
  },
  //删除地址
  delAddr: function (e) {
    var _this = this
    var oIndex = e.currentTarget.dataset.index
    var openid = app.globalData.logininfo.openid;
    var data = {};
    var arr = _this.data.addrarr
    if (arr[oIndex].isDefault != 1) {
      if (arr[oIndex].id != '' && arr[oIndex].id != null) {
        if (openid != null && openid != "") {
          util.post(api.fetchToken()).then(function (res) {
            if (res.access_token != '') {
              return Promise.resolve({
                access_token: res.access_token
              });
            }
          }).then(function (res) {
            data.openid = openid;
            data.access_token = res.access_token;
            data.param = JSON.stringify({
              "id": arr[oIndex].id,
              "delFlag": 1,
            })
            util.post(api.InsertBasAddressByUser, data).then(function (res) {
              if (res.code == 200) {
                arr.splice(oIndex, 1)
                _this.setData({
                  addrarr: arr
                })
                _this.checkaddrarr();
              }
            });
          });
        }
      } else {
        arr.splice(oIndex, 1)
        _this.setData({
          addrarr: arr
        })
        _this.checkaddrarr();
      }
    }else{
      wx.showToast({
        title: '默认地址无法删除',
        icon: 'none',
        duration: 1500
      })
    }
  },
  //打开选择地址组件
  openAddrPicker: function(e){
    var _this = this
    var dIndex = e.currentTarget.dataset.index
    var dId = e.currentTarget.id
    var info = {}
    info.index = dIndex
    info.id = dId
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          // 未授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.albumInfoPositionStart(info);
            },
            fail: function () {
            }
          })
        } else {
          // 已授权
          _this.albumInfoPositionStart(info);
        }
      }
    })
  },
  /**
   * 位置
   */
  albumInfoPositionStart: function (info) {
    var index = info.index
    var _this = this;
    var arr = _this.data.addrarr
    wx.chooseLocation({
      success: function (res) {
        var value = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (value != null && value.length > 0) {
          arr[index].addName = value
          arr[index].addAddress = address
          arr[index].latitude = latitude
          arr[index].longitude = longitude
          _this.setData({
            addrarr: arr
          })
        } else {
          util.dialogAlert("未选中有效地址")
        }
      }
    })
    _this.checkaddr();
  },
})